<!--
 -----功能插槽使用-----
 添加/修改：add
    例：
 <template #add="{ formData，currentUpdateId }">  【formData：添加字段，currentUpdateId：是否是编辑】
        <el-form-item label="标题">
          <el-input v-model="formData.title" placeholder="请输入" />
        </el-form-item>
</template>
 -->
<template>
  <!-- v-if="((Buttonpermissions('search') && searchDataList.length != 0) || searchDataState) && searchCardState" -->
  <div class="app-container">
    <el-card v-loading="loading" v-if="showSearch" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item :label="item.title" v-for="(item, index) in searchDataList" :key="index">
          <el-input v-if="!item.type" v-model="searchData[item.name]" placeholder="请输入" />
          <personnel v-model="searchData[item.name]" v-else-if="item.type == 'user'"></personnel>
          <personnelMore v-model="searchData[item.name]" v-else-if="item.type == 'userMore'"></personnelMore>
          <el-input
            v-else-if="item.type == 'number'"
            type="number"
            v-model="searchData[item.name]"
            placeholder="请输入"
          />
          <!--  -->

          <!-- value-format="YYYY/MM/DD" -->
          <el-date-picker
            v-else-if="item.type == 'timeday'"
            v-model="searchData[item.name]"
            type="date"
            format="YYYY/MM/DD"
            placeholder="请选择"
          />

          <el-date-picker
            v-else-if="item.type == 'datetime'"
            v-model="searchData[item.name]"
            type="datetime"
            format="YYYY/MM/DD HH:mm:ss"
            placeholder="请选择"
          />
          <el-date-picker
            @change="chooseTimeChange(searchData[item.name])"
            v-else-if="item.type == 'time'"
            v-model="searchData[item.name]"
            type="datetimerange"
            format="YYYY/MM/DD"
            value-format="YYYYMMDD"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
          <el-select
            v-else-if="item.type == 'select' && item!.list!.length > 0"
            v-model="searchData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            allow-create
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.value || items.id"
            />
          </el-select>
          <el-select
            v-else-if="item.type == 'selectLable'"
            v-model="searchData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.label || items.name"
            />
          </el-select>
          <el-select
            v-else-if="item.type == 'multipleSelect'"
            multiple
            v-model="searchData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.label || items.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <slot name="addModel" :TableSelect_change="TableSelect_change" />
    <!-- v-if="Buttonpermissions('add')" v-if="false && Buttonpermissions('pldelete')" -->
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" v-if="isShowAddBtn" :icon="CirclePlus" @click="handleAddbutton">{{
            addText || "新增"
          }}</el-button>
          <el-button type="danger" :icon="Delete" @click="handleAllDelete" v-if="false">{{
            plDelete || "批量删除"
          }}</el-button>
        </div>
        <div class="tabtitle">{{ title }}</div>
        <div>
          <el-button type="primary" :icon="Download" @click="downloadTemFn" v-if="showDownloadTem">下载模版</el-button>
          <el-button type="primary" @click="uploadFileFn" v-if="showUpload"> 导入数据 </el-button>
          <el-tooltip content="下载">
            <el-button v-if="isShowDownLoadFile" type="primary" @click="handleDowcvg" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="need_tab_data ? need_tab_data : tableData"
          :highlight-current-row="true"
          @selection-change="selection_change"
          @sort-change="sort_change"
          @cell-dblclick="celldblclickFn"
        >
          <el-table-column type="selection" width="50" align="center" v-if="need_selection" />
          <template v-for="(item, index) in tableDataRule" :key="index">
            <el-table-column
              show-overflow-tooltip
              :sortable="item.order ? 'custom' : false"
              v-if="
                item.prop == 'update_time' ||
                item.prop == 'create_time' ||
                item.prop == 'last_active_time' ||
                item.prop == 'friend_give_time' ||
                item.prop == 'send_time' ||
                item.prop == 'cash_time' ||
                item.prop == 'create_date_day' ||
                item.prop == 'meetTime' ||
                (item.type && item.type == 'time')
              "
              :prop="item.prop"
              :width="item.width || 200"
              :label="item.label"
              align="center"
            >
              <template v-if="item.Tooltip" #header>
                <el-tooltip class="box-item" effect="dark" :content="item.Tooltip" placement="top">
                  {{ item.prop }}
                </el-tooltip>
              </template>
              <template #default="scope">
                {{ formatDateTime(scope.row[item.prop]) }}
              </template>
            </el-table-column>
            <el-table-column
              v-else-if="item.type == 'file'"
              show-overflow-tooltip
              :sortable="item.order ? 'custom' : false"
              :prop="item.prop"
              :width="item.width || 200"
              :label="item.label"
              align="center"
            >
              <template v-if="item.Tooltip" #header>
                <el-tooltip class="box-item" effect="dark" :content="item.Tooltip" placement="top">
                  {{ item.prop }}
                </el-tooltip>
              </template>
              <template #default="scope">
                <div @click="showFileFn(scope.row, item.prop)" style="text-decoration: underline">
                  {{ scope.row[item.prop] }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              :sortable="item.order ? 'custom' : false"
              v-else-if="item.type && item.type == 'select'"
              :prop="item.prop"
              :width="item.width || 200"
              :label="item.label"
              align="center"
            >
              <template v-if="item.Tooltip" #header>
                <el-tooltip class="box-item" effect="dark" :content="item.Tooltip" placement="top">
                  {{ item.prop }}
                </el-tooltip>
              </template>
              <template #default="scope">
                {{ filSelectFn(scope.row[item.prop], item.list) }}
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              :sortable="item.order ? 'custom' : false"
              v-else-if="item.type && item.type == 'filename'"
              :prop="item.prop"
              :width="item.width || 200"
              :label="item.label"
              align="center"
            >
              <template v-if="item.Tooltip" #header>
                <el-tooltip class="box-item" effect="dark" :content="item.Tooltip" placement="top">
                  {{ item.prop }}
                </el-tooltip>
              </template>
              <template #default="scope">
                <div
                  @click="showFileFn(scope.row, item.assoc, scope.row[item.prop])"
                  style="text-decoration: underline"
                >
                  {{ scope.row[item.prop] }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :sortable="item.order ? 'custom' : false"
              v-else-if="item.prop == 'needButton'"
              fixed="right"
              :prop="item.prop"
              :label="item.label"
              :width="item.width"
              align="center"
            >
              <template v-if="item.Tooltip" #header>
                <el-tooltip class="box-item" effect="dark" :content="item.Tooltip" placement="top">
                  {{ item.prop }}
                </el-tooltip>
              </template>
              <template #default="scope">
                <slot :name="item.slot" :data="scope.row" />
              </template>
            </el-table-column>
            <el-table-column
              :sortable="item.order ? 'custom' : false"
              v-else-if="item.link == true && !item.slot"
              :prop="item.prop"
              :label="item.label"
              :width="item.width"
              align="center"
            >
              <template v-if="item.Tooltip" #header>
                <el-tooltip class="box-item" effect="dark" :content="item.Tooltip" placement="top">
                  {{ item.prop }}
                </el-tooltip>
              </template>
              <template #default="scope">
                <el-link
                  v-if="linkShowState(item, scope.row)"
                  @click="LinkCallBack(item.prop, scope.row)"
                  style="color: blue"
                >
                  {{ scope.row[item.prop] }}</el-link
                >
                <div v-else>
                  {{ scope.row[item.prop] }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :sortable="item.order ? 'custom' : false"
              v-else-if="!item.slot"
              :prop="item.prop"
              :width="item.prop == 'channel' ? 200 || item.width : item.width"
              :label="item.label"
              align="center"
              show-overflow-tooltip
            >
              <template v-if="item.Tooltip" #header>
                <el-tooltip class="box-item" effect="dark" :content="item.Tooltip" placement="top">
                  {{ item.prop }}
                </el-tooltip>
              </template>
              <template #default="scope">
                {{ scope.row[item.prop] }}
              </template>
            </el-table-column>
            <el-table-column
              :sortable="item.order ? 'custom' : false"
              v-else
              :prop="item.prop"
              :width="item.width"
              :label="item.label"
              align="center"
            >
              <template v-if="item.Tooltip" #header>
                <el-tooltip class="box-item" effect="dark" :content="item.Tooltip" placement="top">
                  {{ item.prop }}
                </el-tooltip>
              </template>
              <template #default="scope">
                <slot :name="item.slot" :data="scope.row" />
              </template>
            </el-table-column>
            <el-table-column
              v-if="tableDataRule?.length == index + 1 && showOperate && creationShowTime"
              label="创建时间"
              :width="caocuoWidth"
              align="center"
            >
              <template v-if="item.Tooltip" #header>
                <el-tooltip class="box-item" effect="dark" :content="item.Tooltip" placement="top">
                  {{ formatDateTime(scope.row[item.prop]) }}
                </el-tooltip>
              </template>
              <template #default="scope">
                {{ formatDateTime(scope.row["createTime"]) }}
              </template>
            </el-table-column>

            <el-table-column
              v-if="tableDataRule?.length == index + 1 && showOperate"
              fixed="right"
              label="操作"
              :width="caocuoWidth"
              align="center"
            >
              <template v-if="item.Tooltip" #header>
                <el-tooltip class="box-item" effect="dark" :content="item.Tooltip" placement="top">
                  {{ item.prop }}
                </el-tooltip>
              </template>
              <template #default="scope">
                <div class="addbuttonSty">
                  <el-button
                    type="primary"
                    text
                    bg
                    size="small"
                    v-if="updateShow && (userId == scope.row.createUserId || userId == scope.row.uid || userId == 1)"
                    @click="handleUpdate(scope.row)"
                    >{{ updateText }}</el-button
                  >
                  <el-button
                    type="danger"
                    text
                    bg
                    size="small"
                    v-if="deleteShow && (userId == scope.row.createUserId || userId == scope.row.uid || userId == 1)"
                    @click="handleDelete(scope.row)"
                    >{{ deleteText }}</el-button
                  >
                  <!-- v-show="Buttonpermissions(item.type) && buttonShow(item, scope.row)" -->
                  <el-button
                    v-for="(item, index) in addButtonList"
                    :key="index"
                    text
                    bg
                    type="primary"
                    size="small"
                    v-show="!item.show || scope.row[item.show.name] == item.show.value"
                    @click="handleMoudleButton(item.type, scope.row, findInterface(item.type))"
                    >{{ item.name }}</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </template>
          <!-- <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="pager-wrapper" v-if="needPagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChangeFn"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增' : updateText"
      @close="resetForm"
      :width="formDataWidth"
    >
      <el-form
        :inline="formInline"
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-width="labelWdth"
        label-position="right"
        :style="`align-items: center;`"
      >
        <slot name="add" v-if="dialogVisible" :formData="formData" :currentUpdateId="currentUpdateId" />
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateState">确认</el-button>
      </template>
    </el-dialog>
    <!-- 导入弹框 -->
    <el-dialog v-model="dialogVisibleFile" :title="'导入弹框'" @close="resetForm" width="30%">
      <el-form ref="formRef" label-width="100px" label-position="left">
        <el-form-item prop="actionItemEvolve" label="请选择导入文件">
          <div class="fail">
            <input
              ref="failDrop"
              id="failDrop"
              type="file"
              @change="fileChange"
              style="opacity: 0; width: 100%; height: 100%; position: absolute; top: 0%; left: 0%; z-index: 999"
            />
            <div class="tishi">点击或者拖动上传</div>
          </div>
        </el-form-item>
      </el-form>
      <!-- <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template> -->
    </el-dialog>
    <div id="containerddd"></div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed, onMounted } from "vue"
import { Search, Refresh, CirclePlus, Delete, Download, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"

import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { getToken } from "@/utils/cache/cookies"
import {
  createTableDataApi,
  deleteTableDataApi,
  updateTableDataApi,
  getTableDataApi,
  getTablePl,
  getTablecvg
} from "@/api/table/index"
import { AnyColumns } from "element-plus/es/components/table-v2/src/types"
import { formatDateTime } from "@/utils/index"
import { getFile } from "@/api/file"
import axios from "axios"
import router from "@/router"
import { baseURL } from "@/utils/service"
import { useRoute, useRouter } from "vue-router"
import { upLoadFile } from "@/api/table"
import { useUserStoreHook } from "@/store/modules/user"

let routeHook = useRoute() // 当前访问路由
let routeRHook = useRouter() // 当
let { userId } = useUserStoreHook()

console.log("routeHook", router, routeHook)

// import { defaultOptions, renderAsync } from "docx-preview";

//#region
const failDrop = ref<HTMLElement>() // 导入数据
const dialogVisibleFile = ref(false) // 导入弹框
const fileChange = (e: any) => {
  const file = e.target.files[0]
  fileUpdate(file)
}
/** 上传文件 导入数据 */
const uploadFileFn = () => {
  // dialogVisibleFile.value = true
  let inputs = document.createElement("input")
  inputs.type = "file"
  // inputs.accept =
  inputs.addEventListener("change", fileChange)
  inputs.click()
}
// 调用上传接口
const fileUpdate = (file: any) => {
  console.log(file, "--upLoadFile-")

  //文件上传
  upLoadFile({ file }, findInterface("uploadFile")).then((res: any) => {
    console.log("---", res)

    if (res.code == 200) {
      ElMessage.success("导入成功!")
      resetSearch()
      return
    }
  })
}

onMounted(() => {
  failDrop.value?.addEventListener(
    "drop",
    (ev) => {
      ev.preventDefault()
      const file = ev?.dataTransfer?.files[0]
      console.log(file, "文件")
      fileUpdate(file)
    },
    false
  )
})

//#endregion

//排序规则查询obj
const orderObj = ref<any>({})

const RoleList: AnyColumns = [] //StoreGhook.RolesSelect //权限列表
let formData = reactive<any>({})
//后端排序验证
const sort_change = (context: any) => {
  const { order, prop } = context
  let orderTable = null
  if (order) {
    orderTable = { ascending: "asc", descending: "desc" }[order as string]
    orderObj.value = {
      order: orderTable,
      order_field: prop
    }
  }
  getTableData()
}
//link显示逻辑
const linkShowState = computed(() => {
  return (item: any, row: any) => {
    if (!item.link_show_value) {
      return true
    }
    if (item.link_show_value.indexOf(row[item.link_show_key]) != -1) {
      if (item.link_reverse) {
        return true
      } else {
        return false
      }
    } else {
      if (item.link_reverse) {
        return false
      } else {
        return true
      }
    }
  }
})
// 双击数据
const celldblclickFn = (row, column, cell, event) => {
  // console.log('---celldblclickFn---',row, column, cell, event)
  if (!column.property) {
    return
  } else {
    localStorage.setItem("tableDataRule", JSON.stringify(props.tableDataRule))
    localStorage.setItem("rowTable", JSON.stringify(row))
    localStorage.setItem("rowTableName", props.title)
    routeRHook.push({
      path: "/tableDetails"
    })
  }
}

// 筛选配置显示
const filSelectFn = (val: string, list: any[]) => {
  if (val == undefined || !list) {
    return ""
  }
  let str = ""
  for (let i = 0; i < list.length; i++) {
    let it = list[i]
    if (it.value == val) {
      str = it.label
      break
    }
  }
  return str
}

const deleteShowState = computed(() => {
  return (row: any) => {
    if (!props.delete_show_key) {
      return true
    }
    if (props.delete_show_value.indexOf(row[props.delete_show_key as any]) != -1) {
      if (!props.delete_show_resart) {
        return false
      } else {
        return true
      }
    } else {
      if (!props.delete_show_resart) {
        return true
      } else {
        return false
      }
    }
  }
})
const buttonShow = computed(() => {
  return (item: any, row: any) => {
    if (!item.showkey) {
      return true
    }
    if (item.showValue.indexOf(row[item.showkey]) != -1) {
      if (item.restar) {
        return true
      } else {
        return false
      }
    } else {
      if (item.restar) {
        return false
      } else {
        return true
      }
    }
  }
})
//可调转链接点击回调
const LinkCallBack = (type: any, row: any) => {
  emit("linkCallBack", type, row)
}
const updateShowState = computed(() => {
  return (row: any) => {
    if (!props.update_show_key) {
      return true
    }
    if (props.update_show_value.indexOf(row[props.update_show_key as any]) != -1) {
      if (!props.update_show_resart) {
        return false
      } else {
        return true
      }
    } else {
      if (!props.update_show_resart) {
        return true
      } else {
        return false
      }
    }
  }
})
const handleMoudleButton = (type: string, row: any, Face = "") => {
  emit("buttonMoudle", type, row, Face)
}
const findInterface = (type: string) => {
  return props.operationApi.find((item) => item.type == type)?.interface || ""
}
//权限按钮
const Buttonpermissions = computed(() => {
  return true
})
const ButtonpermissionsHook = (State: string) => {
  // console.log(State)

  return true
  // for (let index = 0; index < props.operationApi.length; index++) {
  //   if (props.operationApi[index].type == State) {
  //     const showState = RoleList.indexOf("/api" + props.operationApi[index].interface) != -1
  //     return showState
  //   } else if (index == props.operationApi.length - 1) {
  //     return false
  //   }
  // }
}
const chaxunState = ref<boolean>(true)
// 时间选择限定范围
const chooseTimeChange = (time: any) => {
  const starTime = JSON.parse(JSON.stringify(time[0]))
  const endTime = JSON.parse(JSON.stringify(time[1]))
  const minTime = new Date(insertStr(insertStr(starTime, 4, "-"), 7, "-")).getTime()
  const maxTime = new Date(insertStr(insertStr(endTime, 4, "-"), 7, "-")).getTime()
  const allow = 2592000000 //30天
  if (maxTime - minTime > allow) {
    ElMessage.warning("选择范围请在30天以内!")
    chaxunState.value = false
  } else {
    chaxunState.value = true
  }
}
function insertStr(soure: string, start: number, newStr: string): string {
  return soure.slice(0, start) + newStr + soure.slice(start)
}
function params(obj: any) {
  let result = ""
  let item
  for (item in obj) {
    if (obj[item] && String(obj[item])) {
      result += `&${item}=${obj[item]}`
    }
  }
  if (result) {
    result = result.slice(1)
  }
  return result
}
const handleDowcvg = () => {
  const svgHttp = baseURL //StoreGhook.testState == 1 ? `https://abox.admin.ssche.cn/api` : `https://test.abox.v2.ssche.cn/api`
  // console.log(props.svgOvj, str, TableSelect_change.value, "--getTablecvg--")
  let params = {
    isCheck: true,
    ...props.addDownLoadAjax
  }
  params["id"] = TableSelect_change.value.map((it) => it.id).join(",")
  getTablecvg(params, findInterface("svg")).then((res: any) => {
    // console.log( typeof res,'-getTablecvg-');
    const blobs = new Blob([res], { type: "application/vnd.ms-excel" })
    // console.log(blobs);
    const url = window.URL.createObjectURL(blobs)
    const a = document.createElement("a")
    a.href = url
    a.download = `${props.title}.xlsx`
    a.click()
    //释放
    window.URL.revokeObjectURL(url)
  })
}
// const timeChange = (item: any) => {
//   searchData[item.name] = searchData[item.name][0] + " 至 " + searchData[item.name][1]
// }
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

const handleCurrentChangeFn = (num: number) => {
  console.log("handleCurrentChangeFn", num)

  handleCurrentChange(num)
  getTableData()
}

console.log(paginationData, "--paginationData--")

let searchData = reactive<any>({}) //局部查询字段
const loading = ref<boolean>(false)
const tableData = ref<any>([]) //表格
const TableSelect_change = ref<any>([]) //table选择数组
const dialogVisible = ref<boolean>(false)
const currentUpdateId = ref<undefined | string>(undefined) //ID进行赋值按钮逻辑为编辑操作
const resetForm = () => {
  currentUpdateId.value = undefined
  getTableData()
}
//设置查询的默认值
const setSearch = (data: any) => {
  searchData = reactive<any>({ ...data })
}

//#region 删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`是否确认该操作？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const obj: any = {}
    let id = row[props?.DeleteIdValue ? props.DeleteIdValue : props.DeleteId]
    obj[props.DeleteId] = id
    deleteTableDataApi([id], findInterface("delete")).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//自动执行编辑函数
const handleUpdateFun = (row: any) => {
  currentUpdateId.value = "1"
  formData = reactive({ ...row })
  emit("openAddCallBack")
  dialogVisible.value = true
}
//修改
const handleUpdate = (row: any) => {
  if (props.needAUpdateFun) {
    emit("formDataUpdate", row)
    return
  }
  handleUpdateFun(row)
}

const props = withDefaults(
  defineProps<{
    operationApi?: { type: string; interface: string }[]
    //局部查询  普通字段查询 name:查询字段，title:标题
    //         列表查询字段 name:查询字段，title:标题，type:'select',list:[]
    //           时间段查询 name:查询字段，title:标题，type:'time'
    searchDataList?: {
      name: string
      title: string
      type?: string
      list?: { value: any; label: any; name?: string; id: string }[]
    }[]
    //table表格展示配置项   【slot可自定义，避免slot冲突参考功能插槽】
    // {
    //   prop: string
    //   label: string
    //   slot?: string
    //   width?: string
    //   link::boolean
    // link_reverse: false,//是否取反
    // link_show_key: "channle",
    // link_show_value: ["汇总数据"],
    // }[]
    tableDataRule?: any
    //删除当前表单的key
    DeleteId?: string
    //删除当前表单的Value[没有就默认以Key值显示Value]
    DeleteIdValue?: any
    //添加表单rule验证
    formRules?: { [name: string | number]: any }
    //是否需要手动添加/编辑【点击添加按钮前的数据整理，设置为true ，父组件需接收 formDataAdd 事件】 next:handleCreate
    needAddFun?: boolean //默认自动添加
    //是否需要手动修改【点击修改按钮前的数据整理回显】
    needAUpdateFun?: boolean //默认自动修改设置为true ，父组件需接收 formDataUpdate 事件 next:handleUpdateFun
    //是否需要某些栏目禁止编辑删除按钮【默认不需要】匹配对应栏目ID
    // {
    //   id: ['1'],//根据当前列的ID进行操作按钮的隐藏和操作
    //   deleteButton: { update: true, delate: true }
    // }shequ_tab
    needOperate?: any
    //控制当前列表的删除功能控件和修改功能控件
    button_Type?: any
    //是否有默认查询必填字段 {[name]:value}
    mustSearchData?: any
    //是否需要分页器
    needPagination?: boolean
    //是否需要Table多项框
    need_selection?: boolean
    //table表格标题
    title?: string
    //是否开启选中当前行导出【string参数，一般为当前选中行的某些字段参数】
    svgOvj?: boolean | string
    //控制当前默认操作列表的长度
    caocuoWidth?: string | number
    //修改删除的基础上添加按钮配置项
    addButtonList?: { name: string; type: string }[] //name :按钮名称，type：'事件名称'
    //添加/编辑表单宽度
    formDataWidth?: string
    //同意表格标题的宽度
    labelWdth?: string
    //批量删除按钮标题
    plDelete?: string
    //删除按钮标题
    deleteText?: string
    // 是否显示删除按钮
    deleteShow?: boolean
    //编辑按钮字段
    updateText?: string
    // 是否显示编辑按钮
    updateShow?: boolean
    //是否开启添加表单换行
    formInline?: boolean
    //删除条件显示字段key
    delete_show_key?: any
    delete_show_value?: any
    delete_show_resart?: boolean
    //更新条件显示字段key
    update_show_key?: any
    update_show_value?: any
    update_show_resart?: boolean
    need_pl_fun?: any //批量删除前的回调
    need_tab_data?: any //是否手动添加tableData值
    searchDataState?: boolean //是否只显示查询条件栏，不会调用查询接口，只有回调传递查询参数
    searchCardState?: boolean
    isShowAddBtn?: boolean // 是否显示新增按钮
    isShowDownLoadFile?: boolean // 是否显示下载按钮
    addDownLoadAjax?: any // 下载添加的参数
    isAddArr?: boolean // 是否添加 新增接口 数组包裹
    isUpdataArr?: boolean // 是否在 编辑接口用数据
    isAddAjaxData?: boolean // 是否要 在新增接口添加数据
    addAjaxData?: any // 新增接口追加的数据
    showSearch?: boolean // 是否显示搜索
    showDownloadTem?: boolean // 是否显示 下载模版
    showUpload?: boolean // 是否显示 导入文件
    showOperate?: boolean // 是否显示操作
    creationShowTime?: boolean // 是否显示 创建时间
    UploadArrMerge?: boolean // 上传是否开启合并
    UploadArrMergeKey?: any // 上传合并 的字段
    setAddHeaders?: any // 设置上传的header 头
    addText?: string // 新增按钮文案
  }>(),
  {
    searchCardState: true,
    searchDataState: false,
    operationApi: () => [],
    need_tab_data: false,
    need_pl_fun: false,
    delete_show_key: true,
    update_show_key: true,
    delete_show_resart: true,

    formInline: false,
    deleteText: "删除",

    deleteShow: true,
    updateText: "编辑",
    updateShow: true,
    plDelete: "批量删除",
    searchDataList: () => [
      // { name: "name", title: "用户昵称" },
      // { name: "username", title: "用户账号" }
    ],
    formRules: () => {
      return {
        name: [{ required: true, trigger: "blur", message: "请输入标题" }]
      }
    },
    needAddFun: false,
    needAUpdateFun: false,
    button_Type: { delete: true, update: true },
    mustSearchData: null,
    needPagination: true,
    need_selection: true,
    DeleteId: "id",
    DeleteIdValue: false,
    //表格下载需要传递的参数
    svgOvj: false,
    caocuoWidth: "180",
    addButtonList: () => [],
    formDataWidth: "30%",
    labelWdth: "140px",
    isShowAddBtn: true,
    isShowDownLoadFile: true,
    addDownLoadAjax: {},
    isAddArr: true,
    isUpdataArr: true,
    isAddAjaxData: false,
    addAjaxData: {},
    showSearch: true,
    showDownloadTem: false,
    showUpload: false,
    showOperate: true,
    creationShowTime: true,
    UploadArrMerge: false,
    UploadArrMergeKey: {},
    setAddHeaders: "",
    addText: ""
  }
)

const selection_change = (row: any) => {
  TableSelect_change.value = row
}
const emit = defineEmits<{
  //刷新回调
  (e: "Refresh"): void
  //新增用户前【数据添加前的处理】
  (e: "formDataAdd", formData: any, flag: any): void
  //修改用户前【数据回显至表单的处理】
  (e: "formDataUpdate", row: any): void
  //表格操作按钮
  (e: "buttonMoudle", row: any, type: string | number, Face: string): void
  //添加或者编辑成功后的回调
  (e: "addCallback"): void
  //查询功能的回调
  (e: "searchCallback", searchData: any): void
  (e: "openAddCallBack"): void
  //可跳转链接点击回调
  (e: "linkCallBack", type: any, row: any): void
}>()
let timer: any = null
//重置
const resetSearch = () => {
  for (const key in searchData) {
    searchData[key] = ""
  }
  searchObj.value = {}
  emit("searchCallback", searchObj.value)
  loading.value = true
  getTableData()
}
const searchObj = ref<any>({})
//局部查询接口
const handleSearch = () => {
  if (!chaxunState.value) {
    ElMessage.warning("选择范围请在30天以内!")
    return
  }
  const searchCopy = { ...searchData }
  for (const key in searchCopy) {
    if (Array.isArray(searchCopy[key]) && (key == "channel" || key == "person_charge")) {
      searchCopy[key] = searchCopy[key].join(",")
    }
  }
  searchObj.value = { ...searchCopy }
  props.searchDataList.forEach((item) => {
    if (item.type == "time") {
      if (searchObj.value[item.name]) {
        searchObj.value[item.name] = searchObj.value[item.name][0] + " 至 " + searchObj.value[item.name][1]
      }
    }
  })
  for (const key in searchObj.value) {
    if (searchObj.value[key] === "") {
      delete searchObj.value[key]
    }
  }
  if (!props.searchDataState) {
    getTableData()
  }
  emit("searchCallback", searchObj.value)
}
//是否强制刷新缓存
const refreshState = ref<boolean>(false)
//表单查询
const getTableData = () => {
  if (!ButtonpermissionsHook("search")) {
    return
  }
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    loading.value = true
    let params = {
      page: props.needPagination ? paginationData.currentPage : "",
      pageSize: props.needPagination ? paginationData.pageSize : "",
      ...searchObj.value,
      ...(props.mustSearchData ? props.mustSearchData : {}),
      refresh: refreshState.value ? true : false,
      ...orderObj.value
      // name: searchData.name || undefined,
      // path: searchData.path || undefined
    }
    // console.log(params,paginationData,props.needPagination, "--params--")
    if (!findInterface("search")) {
      loading.value = false
      return
    }
    getTableDataApi(params, findInterface("search"))
      .then((res: any) => {
        console.log(res, "----")

        paginationData.total = res.data.total //总页数赋值
        tableData.value = res?.data?.records || res.data
        loading.value = false
        refreshState.value = false
        // orderObj.value = {}
        // emit("addCallback")
      })
      .catch(() => {
        loading.value = false
      })
  }, 300)
}
//批量删除
const handleAllDeletePlay = () => {
  ElMessageBox.confirm(`是否确认该操作？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const delArr: any = []
    TableSelect_change.value.forEach((item: any) => {
      delArr.push(item[props.DeleteId])
    })
    const obj: any = {}
    obj[props.DeleteId] = delArr
    getTablePl(obj, findInterface("pldelete")).then(() => {
      ElMessage.success("操作成功")
      getTableData()
    })
  })
}
const handleAllDelete = () => {
  if (TableSelect_change.value.length == 0) {
    ElMessage.error("请至少选中一行!")
    return
  }
  if (props.need_pl_fun) {
    props.need_pl_fun(TableSelect_change.value).then(() => {
      handleAllDeletePlay()
    })
  } else {
    handleAllDeletePlay()
  }
}

/** 下载 导入文件模版  */
const downloadTemFn = () => {
  getTablecvg({}, findInterface("downloadTem")).then((res: any) => {
    // console.log( typeof res,'-getTablecvg-');
    const blobs = new Blob([res], { type: "application/vnd.ms-excel" })
    // console.log(blobs);
    const url = window.URL.createObjectURL(blobs)
    const a = document.createElement("a")
    a.href = url
    a.download = `${props.title}模版.xlsx`
    a.click()
    //释放
    window.URL.revokeObjectURL(url)
  })
}

//刷新表格
const handleRefresh = () => {
  emit("Refresh")
  refreshState.value = true
  getTableData()
}
/**查看文件*/
const showFileFn = (it: any, name: string, filename?: string) => {
  console.log(it, "showFileFn", name)
  localStorage.setItem("tabFil", JSON.stringify(it))
  localStorage.setItem("tabFilname", name)
  localStorage.setItem("tabFilname_name", filename || "")
  router.push({
    path: "/filebox"
  })
}

const formRef = ref<FormInstance | null>(null)
const handleAddbutton = () => {
  //添加清空form表单
  formData = reactive({})
  dialogVisible.value = true
  emit("openAddCallBack")
  formRef?.value?.resetFields()
}
const handleCreateState = () => {
  if (props.needAddFun) {
    //通过父组件进行数据整理
    emit("formDataAdd", formData, currentUpdateId.value)
  } else {
    handleCreate(formData)
  }
}
const handleCreate = (formData: any) => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      // formData.is_menu = JSON.stringify(formData.is_menu)
      if (currentUpdateId.value === undefined) {
        if (props.isAddAjaxData) {
          formData = {
            ...formData,
            ...props.addAjaxData
          }
        }
        if (props.UploadArrMerge) {
          let arr = ["standardFileUrl", "standardName"]
          let arrLength = formData[arr[0]]?.split(",") || []
          let arrLengthName = formData[arr[1]]?.split(",") || []
          let promiseAJAX = arrLength.map((it, i) => {
            let it_formdata = {
              ...formData,
              standardFileUrl: arrLength[i],
              standardName: arrLengthName[i]
            }
            return createTableDataApi(it_formdata, findInterface("add"), props.isAddArr, props.setAddHeaders)
          })
          if (arrLength.length == 0) {
            createTableDataApi(formData, findInterface("add"), props.isAddArr, props.setAddHeaders).then((res) => {
              ElMessage.success("新增成功")
              emit("addCallback")
              dialogVisible.value = false
              getTableData()
            })
          } else {
            Promise.all(promiseAJAX).then(() => {
              ElMessage.success("新增成功")
              emit("addCallback")
              dialogVisible.value = false
              getTableData()
            })
          }
        } else {
          createTableDataApi(formData, findInterface("add"), props.isAddArr, props.setAddHeaders).then(() => {
            ElMessage.success("新增成功")
            emit("addCallback")
            dialogVisible.value = false
            getTableData()
          })
        }
      } else {
        let params: any
        if (props.isAddArr || props.isUpdataArr) {
          params = [
            {
              ...formData
            }
          ]
        } else {
          params = {
            ...formData
          }
        }
        updateTableDataApi(params, findInterface("update")).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getTableData()
        })
      }
    } else {
      return false
    }
  })
}
//方法/变量暴漏
defineExpose({ handleCreate, handleUpdate, handleUpdateFun, getTableData, handleDowcvg, resetSearch, setSearch })
/** 监听分页参数的变化 */
watch([() => paginationData.page, () => paginationData.page_count], getTableData as any, { immediate: true })
</script>
<style scoped lang="scss">
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.pager-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.tabtitle {
  color: var(--el-text-color-primary);
  font-size: 16px;
  font-weight: 700;
}
.addbuttonSty {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  .el-button {
    margin-top: 10px;
    // width: 50px;
    // height: 30px;
    margin-left: 10px;
  }
}
.fail {
  width: 100%;
  height: 8vw;
  border: 1px solid #dcdfe6;
  position: relative;
  input {
    width: 100%;
    height: 100%;
  }
  .tishi {
    position: absolute;
    color: gray;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(50%);
    width: 100%;
    text-align: center;
    &::after {
      content: "";
      position: absolute;
      display: block;
      background: url("../../assets/power/yun.png") no-repeat;
      background-size: 100% 100%;
      width: 100px;
      height: 100px;
      // top: -265%;
      bottom: 10px;
      left: 50%;
      margin-left: -50px;
    }
  }
}
</style>
